package com.helloworld.service;

import com.helloworld.mapper.User_RoleMapper;
import com.helloworld.pojo.Role;
import com.helloworld.pojo.User;
import com.helloworld.pojo.User_Role;
import com.helloworld.vo.Role.RoleAddReq;
import com.helloworld.vo.User.UserInfo;
import com.helloworld.vo.User.UserUpdateReq;
import com.helloworld.vo.User_Role.User_RoleAddReq;
import com.helloworld.vo.User_Role.User_RoleInfo;
import com.helloworld.vo.User_Role.User_RoleUpdateReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class User_RoleService {

    @Autowired
    private User_RoleMapper user_roleMapper;

    public Integer  addUser_Role(User_RoleAddReq req){
        User_Role user_role = User_Role.builder()
                .id(req.getId())
                .userId(req.getUserId())
                .roleId(req.getRoleId())
                .build();
        user_roleMapper.addUser_Role(user_role);
        return user_role.getId();
    }

    public void updateUser_Role(User_RoleUpdateReq req) {
        User_Role user_role = User_Role.builder()
                .id(req.getId())
                .userId(req.getUserId())
                .roleId(req.getRoleId())
                .build();
        user_roleMapper.updateUser_Role(user_role);
    }

    public void deleteUser_Role(Integer id) {
        user_roleMapper.deleteUser_Role(id);
    }

    public User_RoleInfo queryUser_RoleById(Integer  id){
        User_Role user_role =  user_roleMapper.queryUser_RoleById(id);
        if(null ==  user_role){
            // throw new RuntimeException("user cannot be found by id=" + id);
            return null;
        }
        return User_RoleInfo.builder()
                .id(user_role.getId())
                .userId(user_role.getUserId())
                .roleId(user_role.getRoleId())
                .build();
    }

    public List<User_RoleInfo> queryUser_RoleList(String nameLike) {
        List<User_Role> user_roles =  user_roleMapper.queryUser_RoleList(nameLike);
        if(CollectionUtils.isEmpty(user_roles)) {
            return new ArrayList<>();
        }
        return user_roles.stream().map(user_role -> {
            return User_RoleInfo.builder()
                    .id(user_role.getId())
                    .userId(user_role.getUserId())
                    .roleId(user_role.getRoleId())
                    .build();
        }).collect(Collectors.toList());
    }


}
